/**
 * (created at 2011-1-22)
 */
package qiushuo.mysqlparser.ast.expression.primary;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import qiushuo.mysqlparser.ast.expression.Expression;
import qiushuo.mysqlparser.generator.SQLType;

/**
 * @author <a href="mailto:QiuShuo1985@gmail.com">QIU Shuo</a>
 */
public class MatchExpression extends PrimaryExpression {
    public static enum Modifier {
        IN_BOOLEAN_MODE,
        IN_NATURAL_LANGUAGE_MODE,
        IN_NATURAL_LANGUAGE_MODE_WITH_QUERY_EXPANSION,
        WITH_QUERY_EXPANSION
    }

    private final List<String> columns;
    private final Expression pattern;
    private final Modifier modifier;

    /**
     * @param modifier optional
     */
    public MatchExpression(List<String> columns, Expression pattern, Modifier modifier) {
        if (columns == null || columns.isEmpty()) {
            this.columns = Collections.emptyList();
        } else if (columns instanceof ArrayList) {
            this.columns = columns;
        } else {
            this.columns = new ArrayList<String>(columns);
        }
        this.pattern = pattern;
        this.modifier = modifier;
    }

    @Override
    public String generateSql(SQLType type) {
        switch (type) {
        case MySQL:
            StringBuilder sb = new StringBuilder();
            sb.append("MATCH (");
            boolean isFst = true;
            for (String col : columns) {
                if (isFst) {
                    isFst = false;
                } else {
                    sb.append(", ");
                }
                sb.append(col);
            }
            sb.append(") AGAINST (");
            sb.append(pattern);
            if (modifier != null) {
                switch (modifier) {
                case IN_BOOLEAN_MODE:
                    sb.append(" IN BOOLEAN MODE");
                    break;
                case IN_NATURAL_LANGUAGE_MODE:
                    sb.append(" IN NATURAL LANGUAGE MODE");
                    break;
                case IN_NATURAL_LANGUAGE_MODE_WITH_QUERY_EXPANSION:
                    sb.append(" IN NATURAL LANGUAGE MODE WITH QUERY EXPANSION");
                    break;
                case WITH_QUERY_EXPANSION:
                    sb.append(" WITH QUERY EXPANSION");
                    break;
                }
            }
            sb.append(')');
            return sb.toString();
        default:
            throw new UnsupportedOperationException("only mysql sql can be generated");
        }
    }
}
